<?php

namespace GuanChanghu\Library\Http\Middleware;


use GuanChanghu\Library\Facades\RSA;
use Closure;
use JsonException;

/**
 * Class RequestDecrypt
 * @tag encryption free
 * @package GuanChanghu\Library\Http\Middleware
 */
class RequestDecrypt
{
    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws JsonException
     */
    public function handle($request, Closure $next)
    {
        if (config('guan-changhu.encrypt.clients_encrypt_enable')[$request->route('client')]) {
            $request->replace($this->decrypt($request->get('encrypted')));
        }

        return $next($request);
    }

    /**
     * @param string $encrypted
     * @return array
     * @throws JsonException
     */
    protected function decrypt(string $encrypted): array
    {
        return json_decode(RSA::client('decrypt')->decrypt($encrypted), true, 512, JSON_THROW_ON_ERROR);
    }
}
